<?php

class Mail extends Tut_Model {

    public $id;
    public $mail_type_id;
    public $name;
    public $subject;
    public $plain_source;
    public $html_source;
    public $language_id;
    public $date;
    
    public $from;
    public $from_name;
    public $to;
    public $to_name;
    public $aConfig;

    public function __construct() {
        parent::__construct();
        $this->_load();
    }

    public function add(array $aProduct) {
        if (empty($aProduct)) {
            return false;
        }

        $aProduct = $this->_prepareArrInsert($aProduct);
        if ((bool) $this->db->insert('product', $aProduct)) {
            return $aProduct;
        }
        return false;
    }

    public function save($iId, $iUserId) {
        if (empty($iId) || empty($iUserId)) {
            return false;
        }

        $aSavedProduct = array(
            'user_id' => $iUserId,
            'product_id' => $iId,
            'date' => time()
        );

        if ((bool) $this->db->insert('saved_product', $aSavedProduct)) {
            return $iId;
        }

        return false;
    }

    public function delete($aIds) {
        if (empty($aIds)) {
            return false;
        }

//        $query = "DELETE FROM tut_product WHERE id IN( " . implode(',', array_values($aIds))  . ")";
        $sql = "UPDATE tut_product SET is_deleted=1 WHERE id IN( " . implode(',', array_values($aIds)) . ")";
        $query = $this->db->query($sql);
        if ($this->db->affected_rows() > 0) {
            return true;
        }

        return false;
    }

    public function gets($offset = 0, $numRow = 10) {
        $oProduct = $this->db->select('p.id, p.name, p.summary, p.description, 
            pc.name as category, p.total_view, p.total_like, p.date, p.image, sp.user_id as user_saved')
                ->from('product p')
                ->join('product_category pc', 'p.product_category_id = pc.id', 'left')
                ->join('language l', 'p.language_id = l.id', 'left')
                ->join('saved_product sp', 'p.id = sp.product_id', 'left')
                ->join('level le', 'p.level_id = le.id', 'left')
                ->where(array('p.is_actived' => 1, 'p.is_deleted' => 0))
                ->limit($numRow, $offset)
                ->order_by('order', 'asc')
                ->get();


        $aProduct = array();
        $this->load->library('encrypt');
        if ($oProduct->num_rows() > 0) {
            foreach ($oProduct->result() as $product) {
                $product->date = date('Y-m-d', $product->date);
                //$product->id = $this->encrypt->encode($product->id, $this->config->item('encode_id'));
                $aProduct[] = $product;
            }
        }

        return $aProduct;
    }

    public function getById($iMailType = 0, $languageName = '') {
        if (empty($iMailType) || empty($languageName)) {
            return false;
        }

        $mail = $this->db->select('m.*, l.name as language_name')
                ->from('mail as m')
                ->join('language as l', 'm.language_id = l.id')
                ->where(array('m.mail_type_id' => $iMailType,
                    'l.name' => $languageName))
                ->get();

        if ($mail->num_rows() > 0) {
            $oMail = $mail->row();
            $oMail->date = date('Y-m-d', $oMail->date);
            $this->assign($oMail);

            return $oMail;
        }

        return false;
    }

    public function countMail() {
        return $this->db->select('*')
                        ->from('mail')
                        ->get()
                        ->num_rows();
    }

    public function sendRegister($oUser = null, $sLanguageName = '') {
        if (!$oUser || empty($sLanguageName)) {
            return false;
        }

        //Create link for confirm.
        $sConfirmedLink = 'http://' . $this->input->server('SERVER_NAME') . $this->input->server('SCRIPT_NAME')
                . '/user/profile/confirm/' . $oUser->sCodeConfirmEmail;
        //Get html source this mail's type.
        $this->getById($this->config->item('register'), $sLanguageName);

        $aReplaceMail = array(
            '%username%' => $oUser->email,
            '%name_service%' => $this->config->item('name_service'),
            '%link%' => $sConfirmedLink,
            '%name%' => $oUser->email
        );

        //Replace %example% with real text
        $this->html_source = str_replace(array_keys($aReplaceMail), array_values($aReplaceMail), $this->html_source);
        $this->from = $this->config->item('email_service');
        $this->from_name = $this->config->item('name_service');
        $this->to = $oUser->email;

        return $this->send();
    }

    public function sendCompleteRegister($oUser = null, $sLanguageName = '') {
        
    }

    public function sendForgetPassword($sEmail = '', $sLanguageName = '') {
        if (empty($sEmail) || empty($sLanguageName)) {
            return false;
        }

        $sCodeChange = $this->createCodeChangePassword();
        $iTimeChange = $this->createTimeChangePassword();

        if (!(bool) $this->user->setInfoChangePassword($sCodeChange, $iTimeChange, $sEmail)) {
            return false;
        }

        $sLink = 'http://' . $this->input->server('SERVER_NAME') . $this->input->server('SCRIPT_NAME')
                . '/user/profile/restorePassword/' . $sCodeChange . '/' . $iTimeChange;

        $this->getById($this->config->item('mail.change_password'), $sLanguageName);

        $aReplaceMail = array(
            '%username%' => $sEmail,
            '%name_service%' => $this->config->item('name_service'),
            '%link%' => $sLink,
            '%name%' => $sEmail
        );
        
        //Replace %example% with real text
        $this->html_source = str_replace(array_keys($aReplaceMail), array_values($aReplaceMail), $this->html_source);
        $this->from = $this->config->item('email_service');
        $this->from_name = $this->config->item('name_service');
        $this->to = $sEmail;

        return $this->send();
    }

    public function createCodeChangePassword() {
        return uniqid();
    }

    public function createTimeChangePassword() {
        //Only can change password around 5 days.
        return time() + 5 * 24 * 60 * 60;
    }

    private function _load() {
        //Load config for mail.
        $this->config->load('config_mail');
        //Create config for sending email.
        $this->aConfig = array(
            'protocol' => $this->config->item('protocol'),
            'smtp_host' => $this->config->item('smtp_host'),
            'smtp_port' => $this->config->item('smtp_port'),
            'mailtype' => 'html'
        );
        //Load library email.
        $this->load->library('email', $this->aConfig);
        //Property of email object.
        $this->_aProp = array('id', "mail_type_id", "name", "subject", "plain_source", "html_source", "language_id", "date");
    }

    private function _prepareArrInsert(array $aArr = null) {
        if (empty($aArr)) {
            return false;
        }

        unset($aArr[$this->config->item('csrf_token_name')]);
        //$aArr['product_category_id'] = $aArr['category'];
        $aArr['product_category_id'] = 1;
        unset($aArr['category']);
        $aArr['language_id'] = $aArr['language'];
        unset($aArr['language']);
        $aArr['level_id'] = $aArr['level'];
        unset($aArr['level']);
        $aArr['date'] = time();
        $aArr['last_update'] = time();
        return $aArr;
    }

    public function send($oMail = null) {
        if (is_object($oMail)) {
            $this->assign($oMail);
        }

        $this->email->set_newline("\r\n");
        $this->email->from($this->from, $this->from_name);
        $this->email->to($this->to);
        $this->email->subject($this->subject);
        $this->email->message($this->html_source);

        if ($this->email->send()) {
            return true;
        } else {
            show_error($this->email->print_debugger());
        }
    }
}
?>
